import pool from '../config/database.js';

export const MedicalModel = {
  async getAllRecords() {
    try {
      const [rows] = await pool.query(`
        SELECT m.*, r.name as patientName 
        FROM medical_records m 
        JOIN residents r ON m.patient_id = r.id 
        ORDER BY m.created_at DESC
      `);
      return rows;
    } catch (error) {
      console.error('Database error:', error);
      throw new Error('Failed to fetch medical records');
    }
  },

  async createRecord(record) {
    try {
      console.log('Creating record with data:', record);
      // 转换日期格式
      const date = record.date.split('T')[0];
      const [result] = await pool.query(
        'INSERT INTO medical_records (patient_id, type, date, doctor, status, notes) VALUES (?, ?, ?, ?, ?, ?)',
        [record.patient_id, record.type, date, record.doctor, record.status, record.notes]
      );
      return result.insertId;
    } catch (error) {
      console.error('Database error:', error);
      throw new Error('Failed to create medical record');
    }
  },

  async updateRecord(id, record) {
    try {
      console.log('Updating record with data:', { id, record });
      // 检查记录是否存在
      const [existing] = await pool.query('SELECT * FROM medical_records WHERE id = ?', [id]);
      if (!existing || existing.length === 0) {
        throw new Error(`Medical record with id ${id} not found`);
      }

      // 转换日期格式
      const date = record.date.split('T')[0];

      const query = `
        UPDATE medical_records 
        SET type = ?, 
            date = ?, 
            doctor = ?, 
            status = ?, 
            notes = ?,
            updated_at = CURRENT_TIMESTAMP
        WHERE id = ?
      `;
      
      const [result] = await pool.query(query, [
        record.type,
        date,
        record.doctor,
        record.status,
        record.notes || '',
        id
      ]);

      if (result.affectedRows === 0) {
        throw new Error('No records were updated');
      }

      return true;
    } catch (error) {
      console.error('Database error:', error);
      throw new Error(`Failed to update medical record: ${error.message}`);
    }
  }
};